<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" @keyup.enter.native="handleFilter()" placeholder="Title" style="width: 200px;" class="filter-item" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter()">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <br/>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" prpo="" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="密码" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.password }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="110" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.sex==0">
            男
          </span>
          <span v-else="scope.row.sex">
            女
          </span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="昵称" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.nickname | statusFilter">{{ scope.row.nickname }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.createtime|newDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="del(row.id)">
            删除
          </el-button>
          <el-button  size="mini" type="danger" @click="handleUserRole(row)">
            分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <br/>

    <el-dialog
      width="300px"
      title="角色分配"
      :visible.sync="dialogRoleVisible"
    >
      <el-table
        ref="multipleTable"
        :data="roleList"
        border
        fit
        highlight-current-row
        size="medium"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column label="角色名">
          <template slot-scope="scope">
            {{ scope.row.rname }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button>
          取消
        </el-button>
        <el-button type="primary" @click="setUserRole()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-pagination
      :current-page="listQuery.page"
      :page-sizes="[3, 5, 15, 20]"
      :page-size="listQuery.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="listQuery.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog width="400px" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="user">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
          <el-select v-model="user.sex" placeholder="请选择性别">
            <el-option
              v-for="item in sexOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="password" label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="user.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'Index',
  data() {
      return {
      list: null,
      roleList:null,
      listLoading: true,
      dialogStatus:'',
      dialogFormVisible: false,//ture显示弹出框 false隐藏弹出框
      dialogRoleVisible:false,
        uid:'',
      sexOptions: [{ 'id': 0, 'name': '男' }, { 'id': 1, 'name': '女' }],
      user:{
        username:'',
        sex:'',
        password:''
      },rules: {
        username:[
          {required:true,message:'请输入真实姓名',trigger:'blur'},
          {min:3,max:5,message: '长度在3到5个字符',trigger: 'blur'}
        ],
        sex:[
          {required:true,message:'请选择性别',trigger:'change'}
        ],
        password:[
          {required:true,message:'请输入密码',trigger:'blur'},
          {min:6,max:11,message: '长度在6到11个字符',trigger: 'blur'}
        ]
      },
      listQuery: {
        page:1,
        limit:3,
        total:0,
        username:''
      },
      formLabelWidth: '80px',
      textMap:{
        update:'用户修改',
        create:'用户添加'
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      axios.post('http://localhost:8080/OAManger_war_exploded/getList',this.listQuery).then(res => {
        console.log(res)
        this.list = res.data.list
        this.listQuery.total = res.data.total
        this.listLoading =  false
      })
      axios.get('http://localhost:8080/OAManger_war_exploded/getRoleList').then(
        res=>{
          this.roleList=res.data
        })
    },
    del(id){
      axios.get(`http://localhost:8080/OAManger_war_exploded/delete/`+id).then(
        res=>{
          if (res.data == 1) {
            this.fetchData()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }
        }
      )
    },
    resetTemp() {
      this.user = {
        username: '',
        sex: '',
        password: ''
      }
    }, handleCreate() {
      // 清空表单
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          axios.post(`http://localhost:8080/OAManger_war_exploded/add`,
            this.user).then(
            res => {
              // eslint-disable-next-line eqeqeq
              if (res.data == 1) {
                this.dialogFormVisible = false
                this.fetchData()
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },handleUpdate(row) {
      this.user = Object.assign({}, row) // copy obj
      console.log(this.user)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          axios.post('http://localhost:8080/OAManger_war_exploded/update',
            this.user
          ).then(res => {
            // eslint-disable-next-line eqeqeq
            if (res.data == 1) {
              this.dialogFormVisible = false
              this.fetchData()
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSizeChange(size) {
      this.listQuery.limit = size
      this.fetchData()
    },
    handleCurrentChange(size) {
      this.listQuery.page = size
      this.fetchData()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },handleUserRole(row){
      //分配角色弹出框
      this.dialogRoleVisible = true
      this.uid = row.id
      axios.get(`http://localhost:8080/OAManger_war_exploded/getRoleListUser/` + row.id).then(
        res=>{
          this.toggleSelection(res.data)
        }
      )
    },toggleSelection(rows){
      console.log(rows)
      this.$refs.multipleTable.clearSelection()
      rows.forEach(row =>{
        this.$refs.multipleTable.toggleRowSelection(
          this.roleList.find(item=>{
            return row.rid === item.rid
          }),true)
      })
    },
    handleSelectionChange(val){
      //分配角色复选框选中
      this.multipleSelection =val
    },setUserRole(){
      //分配角色操作
      const rids =[]
      this.multipleSelection.forEach(r =>{
        rids.push(r.rid)
      })
      if (rids.length>0){
        console.log(rids)
        axios.post(`http://localhost:8080/OAManger_war_exploded/getGrant`,
          {'uid':this.uid,'rids':rids}).then(res=>{
            if (res.data>0){
              this.fetchData()
              this.dialogRoleVisible = false
              this.$notify({
                title:'成功',
                message:'分配角色成功',
                type:'success',
                duration:2000
              })
            }
        })
      } else {
        this.$message({
          message: '请选择角色',
          type: 'warning'
        })
      }
    }
    },filters:{
    newDate(createtime){
      let d = new Date(createtime)
						return d.getFullYear()+"-"+d.getMonth()+"-"+d.getDate()
    },
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  }
}
</script>

<style scoped>

</style>
